package com.tarena.lbs.content.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.pojo.dto.StoreDTO;
import com.tarena.lbs.content.pojo.param.ArticleActionParam;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleActionPageResultVO;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 文章业务模块接口
 */
@Slf4j
@RestController
@Tag(name = "文章相关功能接口")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Operation(summary = "文章分页列表查询")
    @GetMapping("/admin/content/article/list")
    public Result<PageResult<ArticleVO>> pageList(ArticleQuery articleQuery)
            throws BusinessException{
        log.info("文章分页列表查询，参数: {}", articleQuery);
        PageResult<ArticleVO> pageResult = articleService.pageList(articleQuery);
        return new Result<>(pageResult);
    }




    @Operation(summary = "文章新增")
    @PostMapping("/admin/content/article/insert")
    public Result<Void> addArticle(ArticleContentParam param)
        throws BusinessException{
        log.info("新增文章，参数: {}", param);
        return articleService.addArticle(param);
    }


    @Operation(summary = "文章标签集合")
    @GetMapping("/admin/content/article/getArticleLabel")
    public Result<Set<String>> articleLabels(ArticleQuery articleQuery) throws BusinessException {

        return null;
    }


    @Operation(summary = "文章详情")
    @GetMapping("/admin/content/article/get")
    public Result<ArticleVO> articleDetail(String id)throws BusinessException{
        log.info("获取文章详情，id: {}", id);

        // 参数校验
        if (id == null || id.trim().isEmpty()) {
            return Result.fail("-1", "文章ID不能为空");
        }

        try {
            Integer articleId = Integer.parseInt(id);
            ArticleVO articleVO = articleService.getById(articleId);
            if (articleVO == null) {
                return Result.fail("-1", "文章不存在");
            }
            return new Result<>(articleVO);
        } catch (NumberFormatException e) {
            log.error("文章ID格式错误，id: {}", id, e);
            return Result.fail("-1", "文章ID格式错误");
        }
    }


    @Operation(summary = "用户行为记录")
    @PostMapping("/admin/content/article/behavior")
    public Result<Void> articleBehavior(ArticleActionParam param)
        throws BusinessException{
        return Result.success();
    }


    @Operation(summary = "查询已经点赞 收藏 访问过的文章")
    @GetMapping("admin/content/article/getBehaviorList")
    public Result<ArticleActionPageResultVO> getBehaviorLists(ArticleQuery query)
        throws BusinessException{
        return null;
    }
    @Operation(summary = "编辑文章或更新状态")//根据参数智能判断操作类型
    @PostMapping("/admin/content/article/update")
    public Result<Void> updateArticle(ArticleContentParam param)
            throws BusinessException{
        log.info("编辑文章或更新状态，参数: {}", param);
    
        // 验证参数
        if (param == null || param.getId() == null || param.getId() <= 0) {
            return Result.fail("-1","文章ID不能为空");
        }
    
        // 智能判断操作类型：
        // 1. 如果只传递了id和状态参数（没有传递文章标题等内容参数），则执行仅状态更新
        // 2. 如果传递了完整的文章内容参数，则执行完整的文章更新
        if ((param.getArticleTitle() == null || param.getArticleTitle().trim().isEmpty()) &&
            (param.getArticleCategoryId() == null || param.getArticleCategoryId() <= 0) &&
            (param.getArticleDetail() == null || param.getArticleDetail().trim().isEmpty())) {
            // 执行仅状态更新
            log.info("执行仅状态更新操作");
            return articleService.updateArticleStatus(
                    param.getId(),
                    param.getArticleStatus(),
                    param.getOnlineStatus()
            );
        } else {
            // 执行完整的文章更新
            log.info("执行完整文章更新操作");
            return articleService.updateArticle(param);
        }
    }

    @Operation(summary = "删除文章")
    @PostMapping("/admin/content/article/delete")
    public Result<Void> deleteArticle(@RequestParam("id") Integer id) throws BusinessException {
        log.info("删除文章，参数: id = {}", id);

        // 参数校验
        if (id == null || id <= 0) {
            return Result.fail("-1", "文章ID不能为空");
        }


        // 调用服务层执行删除
        return articleService.deleteArticle(id);
    }

    /*@Operation(summary = "获取活动列表（用于推文创作）")
    @GetMapping("admin/marketing/marketingActivity/info/list")
    public Result<PageResult<ActivityDto>> getActivityList(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status) {
        log.info("获取活动列表，pageNo={}, pageSize={}, status={}", pageNo, pageSize, status);
        PageResult<ActivityDto> result = articleService.getActivityList(pageNo, pageSize, status);
        return new Result<>(result);
    }*/

    @Operation(summary = "根据区域查询店铺列表")
    @GetMapping("/admin/content/article/getStoresByArea")
    public Result<List<StoreDTO>> getStoresByArea(
            @RequestParam("cityIds") List<Long> cityIds,
            @RequestParam(defaultValue = "2") Integer level) throws BusinessException {
        log.info("根据区域查询店铺列表，cityIds: {}, level: {}", cityIds, level);
        List<StoreDTO> stores = articleService.getStoresByArea(cityIds, level);
        return new Result<>(stores);
    }

    @Operation(summary = "检查店铺是否存在")
    @GetMapping("/admin/content/article/checkStoreExists")
    public Result<Boolean> checkStoreExists(@RequestParam("storeId") Integer storeId) throws BusinessException {
        log.info("检查店铺是否存在，storeId: {}", storeId);
        Boolean exists = articleService.checkStoreExists(storeId);
        return new Result<>(exists);
    }

}